import {
  findAllStore
} from "../../api/store"
import {
  selectPathBehavior
} from "./behavior"
import {
  getAllAddress
} from "../../api/shippingAddress"
import {
  setStorage
} from '../../utils/storage'
import {
  setDefaultStore
} from "../../api/user"

Page({
  behaviors: [selectPathBehavior],

  data: {
    stores: [],
    latitude: 23.099994, // 经度
    longitude: 113.324520, //纬度
    markers: [{ // 绘制浮标，传入JSON支持多个
      iconPath: "/assets/images/location.png", //浮标图片路径，推荐png图片
      id: 0, // Id支持多个，方便后期点击浮标获取相关信息
      latitude: 23.099994, // 经度
      longitude: 113.324520, //纬度
      width: 50, // 浮标宽度
      height: 50 // 浮标高度
    }]
  },
  selectStore(e) {
    const store = this.data.stores[e.currentTarget.dataset.index];
    this.changeStoreObj(store)
    // 设置默认商铺，下次同一个用户就不需要再次选择商铺了
    setDefaultStore({userid: this.data.userInfo.id, store}).then((res) => {
      const userInfoObj = JSON.parse(JSON.stringify(this.data.userInfo))
      userInfoObj.defaultstore = JSON.parse(JSON.stringify(store))
      setStorage("userInfo", userInfoObj)
      this.setUserInfo(userInfoObj)
    })
    wx.switchTab({
      url: '/pages/list/list',
    })
  },
  async onLoad({isSend}) {
    isSend = (isSend === 'true')
    const {
      data
    } = await findAllStore()
    this.changeIsSend(isSend)
    this.setData({
      stores: data
    })
    if (!isSend) {
      let markers = []
      if (Array.isArray(data)) {
        data.forEach(item => {
          markers.push({
            iconPath: item.imageurl,
            title: item.name,
            latitude: item.latitude,
            longitude: item.longitude,
            width: 50,
            height: 50
          })
        })
      }

      wx.getLocation({
        type: 'gcj02',
        success: res => {
          markers.push({
            iconPath: "/assets/images/location.png",
            latitude: res.latitude, // 经度
            longitude: res.longitude, //纬度
            width: 50,
            height: 50
          })
          this.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            markers
          })
        }
      })
    } 
  },
  toAddress() {
    let that = this
    wx.navigateTo({
      url: (that.data.userInfo ? "/pages/address/address" : "/pages/login/login"),
    })
  }
});